package cn.geminis.data.jpa;

import lombok.Getter;
import lombok.Setter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.Arrays;

@Getter
@Setter
public class PageQuery {
    private Integer pageIndex;
    private Integer pageSize;
    private String[] sort;

    public Sort toSort() {
        if (sort == null) {
            return Sort.unsorted();
        } else {
            return Sort.by(
                    Arrays.stream(sort).map(s -> {
                        var sortValues = s.split(":");
                        var field = sortValues[0];
                        var order = sortValues.length > 1 ? Sort.Direction.valueOf(sortValues[1].toUpperCase()) : Sort.DEFAULT_DIRECTION;
                        return new Sort.Order(order, field);
                    }).toList()
            );
        }
    }

    public Pageable toPageable() {
        if (pageSize == null) {
            return Pageable.unpaged();
        } else {
            return PageRequest.of(pageIndex == null ? 0 : pageIndex, pageSize, toSort());
        }
    }

    public static PageQueryBuilder builder() {
        return new PageQueryBuilder();
    }

    public static class PageQueryBuilder {
        private final PageQuery queryFilter = new PageQuery();

        public PageQuery build() {
            return this.queryFilter;
        }

        public PageQueryBuilder pageIndex(Integer pageIndex) {
            queryFilter.pageIndex = pageIndex;
            return this;
        }

        public PageQueryBuilder pageSize(Integer pageSize) {
            queryFilter.pageSize = pageSize;
            return this;
        }

        public PageQueryBuilder sort(String... sort) {
            queryFilter.sort = sort;
            return this;
        }
    }
}
